package com.bsg.upm.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.bsg.upm.check.CheckResult;
import com.bsg.upm.check.PortCheck;
import com.bsg.upm.constant.DictTypeConstants;
import com.bsg.upm.constant.OperateDictConstants;
import com.bsg.upm.constant.OperateDictTypeConstants;
import com.bsg.upm.dto.PortDto;
import com.bsg.upm.entity.PortEntity;
import com.bsg.upm.entity.SiteEntity;
import com.bsg.upm.entity.SubServEntity;
import com.bsg.upm.entity.UserEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;
import com.bsg.upm.util.DateUtils;
import com.bsg.upm.util.PrimaryKeyUtils;

/**
 * 端口管理业务处理类
 * 
 * @author HCK
 *
 */
@Service
public class PortService extends BaseService {

	@Resource
	private PortCheck portCheck;

	/**
	 * 端口查询
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson list(Map<String, Object> paramMap) throws APIException {
		try {
			// 结果集
			JSONArray results = new JSONArray();

			// 获取指定条件的端口
			List<PortEntity> ports = portDao.list(paramMap);
			for (PortEntity port : ports) {
				// 构建端口展示对象
				PortDto portDto = buildShowDto(port, false);
				results.add(portDto);
			}

			return RespJsonFactory.buildOK(results);
		} catch (Exception e) {
			logger.error("端口查询异常", e);
			throw new APIException("端口查询异常:" + e.getMessage());
		}
	}

	/**
	 * 端口新增
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson save(Map<String, Object> paramMap) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_ADD;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 端口新增检查
			CheckResult chkRS = portCheck.checkSave(paramMap);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			// 构建区域对象
			List<PortEntity> ports = buildPorts(paramMap);
			portDao.batchInsert(ports);

			Integer startPort = (Integer) paramMap.get("startPort");
			Integer endPort = (Integer) paramMap.get("endPort");
			String operateObj = startPort + "-" + endPort;
			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_PORT, operateAcion, operateObj, operateObj,
					ports.get(0).getCreateDateTime());

			return RespJsonFactory.buildCreated();
		} catch (Exception e) {
			logger.error("端口" + operateAcionText + "异常", e);
			throw new APIException("端口" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 端口启用/停用
	 * 
	 * @param id
	 *            端口编码
	 * @param enable
	 *            是否启用
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson enable(String siteId, int[] portValues, boolean enable) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_DISABLE;
		if (enable) {
			operateAcion = OperateDictConstants.ACTION_ENABLE;
		}
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 获取指定条件的端口
			List<PortEntity> ports = portDao.listBySiteIdAndPortValues(siteId, portValues);

			// 端口启停检查
			CheckResult chkRS = null;
			if (enable) {
				chkRS = portCheck.checkEnable(ports);
			} else {
				chkRS = portCheck.checkDisable(ports);
			}
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			// 设置端口状态并更新
			for (PortEntity port : ports) {
				port.setEnabled(enable);
				portDao.updateEnabled(port);
			}

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_PORT, operateAcion, Arrays.toString(portValues),
					Arrays.toString(portValues));

			return RespJsonFactory.buildOK();
		} catch (Exception e) {
			logger.error("端口" + operateAcionText + "异常", e);
			throw new APIException("端口" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 端口删除
	 * 
	 * @param siteId
	 *            站点编码
	 * @param portValues
	 *            端口集合
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson remove(String siteId, int[] portValues) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_REMOVE;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 获取指定条件的端口
			List<PortEntity> ports = portDao.listBySiteIdAndPortValues(siteId, portValues);

			// 端口删除检查
			CheckResult chkRS = portCheck.checkRemove(ports);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			for (PortEntity port : ports) {
				portDao.remove(port.getId());
			}

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_PORT, operateAcion, Arrays.toString(portValues),
					Arrays.toString(portValues));

			return RespJsonFactory.buildNoContent();
		} catch (Exception e) {
			logger.error("端口" + operateAcionText + "异常", e);
			throw new APIException("端口" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 构建端口展示对象
	 * 
	 * @param port
	 *            端口对象
	 * @param showDetail
	 *            是否展示详情
	 * @return 端口展示对象
	 */
	private PortDto buildShowDto(PortEntity port, boolean showDetail) {
		PortDto portDto = new PortDto();
		SiteEntity site = port.getSite();
		portDto.setSiteId(site.getId());
		portDto.setSiteName(site.getName());
		portDto.setId(port.getId());
		portDto.setPortValue(port.getPortValue());
		portDto.setUsed(port.isUsed());
		portDto.setEnabled(port.getEnabled());
		String enabledText = dictTypeCache.getTextFromCache(DictTypeConstants.STATUS_ENABLED,
				String.valueOf(port.getEnabled()));
		portDto.setEnabledText(enabledText);
		SubServEntity subserv = port.getSubServ();
		if (subserv != null) {
			portDto.setServName(subserv.getServ().getServName());
		}
		portDto.setCreateDateTime(DateUtils.dateTimeToString(port.getCreateDateTime()));
		portDto.setCreateLoginUserName(port.getCreateUserLoginName());
		return portDto;
	}

	/**
	 * 构建端口对象集合
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return 端口对象集合
	 */
	private List<PortEntity> buildPorts(Map<String, Object> paramMap) {
		List<PortEntity> ports = new ArrayList<PortEntity>();
		Integer startPort = (Integer) paramMap.get("startPort");
		Integer endPort = (Integer) paramMap.get("endPort");
		for (int i = startPort.intValue(); i <= endPort.intValue(); i++) {
			PortEntity port = new PortEntity();
			port.setId(PrimaryKeyUtils.uniqueId());
			SiteEntity site = new SiteEntity();
			site.setId((String) paramMap.get("site"));
			port.setSite(site);
			port.setPortValue(i);
			port.setEnabled(true);
			port.setUsed(false);
			UserEntity user = getUser();
			String username = user.getUsername();
			port.setCreateUserLoginName(username);
			port.setCreateDateTime(systemDao.getCurrentDateTime());
			ports.add(port);
		}
		return ports;
	}

}
